/* The example shows
*/
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
import java.io.* ;
import java.net.* ;

public class DataExchangeServer extends JFrame {
   JLabel		addresses = new JLabel("..........................");
   JTextArea		ta = new JTextArea(40, 70);
   ServerSocket		svrSocket = null;

   DataExchangeServer() {
	Container c = getContentPane();

	c.add(addresses, BorderLayout.SOUTH);
	ta.setFont(new Font("MONOSPACED", Font.PLAIN, 12) );
	c.add(new JScrollPane(ta), BorderLayout.CENTER) ;
	setTitle("Data Exchange Server") ;
	setSize(600, 400); show() ;
	
   }

   public static void main( String arg[] ) {
	DataExchangeServer fm =  new DataExchangeServer() ;
	fm.addWindowListener( new WindowAdapter () {
		public void windowClosing(WindowEvent e) {
			System.exit(0); } } );

	// ----------------------------------------------------------------
	// Create a server socket listenning on port 8900 which is 
	// special port number that allows client and server programs run
	// on the same machine. However, TCP/IP must be installed on that
	// machine even if the client and server are running on the same
	// machine.
	// ----------------------------------------------------------------
	try { fm.svrSocket = new ServerSocket(8900); }
	catch (IOException e) { e.printStackTrace(); }

	try { fm.addresses.setText("Host IP Address: " + InetAddress.getLocalHost().getHostAddress() +
			     " \tHost name: " + InetAddress.getLocalHost().getHostName() );
	} catch (UnknownHostException e) {}

	while (true) {
	    try {
		Socket connSocket = fm.svrSocket.accept() ;
		new ExchangeThread( connSocket, fm.ta ).start();
	    }
	    catch (IOException e) { e.printStackTrace(); }
	}
  }
}

class ExchangeThread extends Thread {
   Socket	connSocket;
   JTextArea    ta;
   int		clientN;

   public ExchangeThread( Socket s, JTextArea a) { connSocket = s; ta = a; }

   public void run() {
	Thread r = new SocketReadThread(connSocket, ta);
	Thread w = new SocketWriteThread(connSocket);
	r.start();  w.start();
	try {
		r.join();
		w.join();
		connSocket.close(); 
	}
	catch (IOException ioe) {}
	catch (InterruptedException ite) {}
   }
}
